package com.weipai;

import org.apache.rocketmq.client.producer.DefaultMQProducer;

import static com.weipai.ServerTcp.producer;

public class ShutdownHook {
        /**
         * 33      * 注册hook程序，保证线程能够完整执行
         * 34      * @param checkThread
         * 35
         */
        public static void addShutdownHook(final Thread checkThread,final DefaultMQProducer producer) {
            //为了保证TaskThread不在中途退出，添加ShutdownHook
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    System.out.println("收到关闭信号，hook起动，开始检测线程状态 ...");
//                    for (int i = 0; i < 100; i++) {
//                        if (checkThread.getState() == State.TERMINATED) {
//
//                            System.out.println("检测到线程执行完毕，退出hook");
//                            return;
//                        }
//                        ShutdownHook.sleep(100);
//                    }
                    producer.shutdown();
                    System.out.println("检测超时，放弃等待，退出hook，此时线程会被强制关闭");
                }

            });
        }
        private static void sleep(long millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

}